<template>
  <div class="box">
    <!-- 搜索用户 -->
    <div style="display: flex;justify-content: space-between;">
      <div class="search-box">
        <div>
          <el-input v-model="inputmobile" placeholder="请输入用户手机号" maxlength="11" />
          <el-input v-model="inputName" placeholder="请输入用户昵称" maxlength="6" />
        </div>
        <div>
          <el-button type="primary" icon="el-icon-search" class="search-but" @click="searchSubmit()">搜索</el-button>
        </div>
      </div>
      <!-- 添加用户 -->
      <div>
        <el-button type="primary" class="button" icon="el-icon-plus" @click="addFormVisible = true">添加用户</el-button>
      </div>
    </div>
    <!-- admin列表 -->
    <el-table v-loading="loading" border style="width: 100%" :data="tableData" @row-click="clickRow">
      <el-table-column prop="id" label="ID" width="180" align="center" />
      <el-table-column prop="username" label="用户昵称" align="center" />
      <el-table-column prop="mobile" label="用户手机" align="center" />
      <el-table-column label="用户状态" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.id === 1">
            <el-switch v-model="scope.row.admin_status" :active-text="scope.row.admin_status === 1 ? '正常':'停用'"
              :active-value="1" :inactive-value="2" disabled @change="switchChange(scope.row.admin_status)" />
          </div>
          <div v-else>
            <el-switch v-model="scope.row.admin_status" :active-text="scope.row.admin_status === 1 ? '正常':'停用'"
              :active-value="1" :inactive-value="2" @change="switchChange([scope.row.admin_status,scope.row.id])" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="notes" label="备注信息" align="center" />
      <el-table-column prop="itime" label="添加时间" align="center" />
      <el-table-column prop="is_super" label="超级用户" :filters="[{ text: '是', value: 1 }, { text: '否', value: 0 }]"
        :filter-method="filterTag" filter-placement="bottom-end" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_super === '1' ? 'primary' : 'success'"
            disable-transitions>{{ scope.row.is_super === '1' ? '是':'否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button v-if="scope.row.id !== 1" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="warning" @click="editPwdVisible = true">修改密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加 -->
    <el-dialog title="添加" :visible.sync="addFormVisible">
      <el-form ref="addFormVisibleData" :model="addFormVisibleData" :rules="rules">
        <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="username">
          <el-input v-model="addFormVisibleData.username" autocomplete="off" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model.number="addFormVisibleData.mobile" autocomplete="off" placeholder="请输入用户手机号"
            maxlength="11" />
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth" prop="password" :rules="[
            {required:true,message:'请输入用户初始密码',trigger:'blur'},
            {min:6,max:16,message:'长度在 6 到 16 个字符',trigger:'blur'}
          ]">
          <el-input :key="passwordType" ref="password" v-model="addFormVisibleData.password" :type="passwordType"
            placeholder="请输入用户密码" name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
        <el-form-item label="是否超管" :label-width="formLabelWidth" prop="is_super">
          <el-select v-model="addFormVisibleData.is_super">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息" :label-width="formLabelWidth">
          <el-input v-model="addFormVisibleData.notes" autocomplete="off" maxlength="30" placeholder="请输入备注信息" />
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="colseFormVisible('addFormVisibleData')">取 消</el-button>
        <el-button type="primary" @click="addConfirm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="editFormVisible">
      <el-form ref="editFormVisibleData" :model="editFormVisibleData" :rules="rules">
        <div v-if="editFormVisibleData.id == 1">
          <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="username">
            <el-input v-model="editFormVisibleData.username" autocomplete="off" placeholder="请输入用户昵称" disabled />
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="username">
            <el-input v-model="editFormVisibleData.username" autocomplete="off" placeholder="请输入用户昵称" />
          </el-form-item>
        </div>
        <el-form-item label="用户手机" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model.number="editFormVisibleData.mobile" autocomplete="off" placeholder="请输入用户手机号"
            maxlength="11" />
        </el-form-item>
        <el-form-item label="是否超管" :label-width="formLabelWidth" prop="is_super">
          <div v-if="editFormVisibleData.id === 1">
            <el-select v-model="editFormVisibleData.is_super" disabled>
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </div>
          <div v-else>
            <el-select v-model="editFormVisibleData.is_super">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="备注信息" :label-width="formLabelWidth">
          <el-input v-model="editFormVisibleData.notes" autocomplete="off" maxlength="30" placeholder="请输入备注信息" />
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="colseFormVisible('editFormVisibleData')">取 消</el-button>
        <el-button type="primary" @click="editConfirm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改管理密码弹窗 -->
    <el-dialog title="修改密码" :visible.sync="editPwdVisible" width="30%">
      <el-form ref="pwdFrom" :model="pwdFrom" :rules="pwdFromRules">
        <el-form-item label="新密码" :label-width="formLabelWidth" prop="new_pwd">
          <el-input :key="passwordType" ref="password" v-model="pwdFrom.new_pwd" :type="passwordType" placeholder="新密码"
            name="password" tabindex="2" auto-complete="on" clearable @keyup.enter.native="handleLogin" />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="confirm_pwd">
          <el-input :key="passwordType" ref="password" v-model="pwdFrom.confirm_pwd" :type="passwordType"
            placeholder="确认密码" name="password" tabindex="2" auto-complete="on" clearable
            @keyup.enter.native="handleLogin" />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="colseFormVisible('pwdFrom')">取 消</el-button>
        <el-button type="primary" @click="ediePwdConfirm()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 翻页 -->
    <el-pagination class="pagination" background layout="total,prev, pager, next" :total="total" :page-size="pageSize"
      @current-change="handleCurrentChange" />
  </div>
  </div>
</template>

<script>
  import {
    adminList,
    adminEdit,
    adminDel,
    adminEditPwd,
    adminStatusSwitch,
    passIdGet,
    adminAdd
  } from '@/api/admin.js'
  export default {
    name: 'Admin',
    data() {
      return {
        tableData: [],
        total: 0,
        pageSize: 10,
        currPage: 1,
        loading: true,
        // 搜索
        inputmobile: '',
        inputName: '',
        // 点击行的数据信息
        clickRowData: [],
        // 密码
        passwordType: 'password',
        // 删除确认框
        delVisible: false,
        // 修改密码
        editPwdVisible: false,
        // 表单
        editFormVisible: false,
        addFormVisible: false,
        formLabelWidth: '120px',
        commonDialogTitle: '',
        // 弹窗
        editFormVisibleData: {
          id: '',
          username: '',
          mobile: '',
          password: '',
          is_super: '',
          notes: ''
        },
        addFormVisibleData: {
          username: '',
          mobile: '',
          password: '',
          is_super: '',
          notes: ''
        },
        // 表单验证
        rules: {
          username: [{
              required: true,
              message: '请输入用户名称',
              trigger: 'blur'
            }
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          mobile: [{
              required: true,
              message: '请输入用户手机',
              trigger: 'blur'
            },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入正确的手机号格式',
              trigger: 'blur'
            }
          ],
          is_super: [{
            required: true,
            message: '请输入选择用户超管身份',
            trigger: 'blur'
          }]
        },
        // 修改密码
        pwdFrom: {
          new_pwd: '',
          confirm_pwd: ''
        },
        pwdFromRules: {
          new_pwd: [{
              required: true,
              message: '请输入新密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 16,
              message: '长度在 6 到 16 个字符',
              trigger: 'blur'
            }
          ],
          confirm_pwd: [{
              required: true,
              message: '请输入确认密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 16,
              message: '长度在 6 到 16 个字符',
              trigger: 'blur'
            }
          ]
        }
      }
    },
    created() {
      // 列表初始获取
      this.getList(1)
    },
    methods: {
      // 管理列表
      getList(num) {
        this.loading = true
        adminList({
          page: this.currPage,
          size: this.pageSize,
          mobile: this.inputmobile,
          name: this.inputName
        }).then(res => {
          // console.log(res.data.total_num)
          this.loading = false
          this.tableData = res.data.list
          this.total = res.data.total_num
        })
      },
      // 当前页改变时触发 跳转其他页
      handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.currPage = val
        this.getList(val)
      },

      // 显示密码
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      // 取消公共弹窗
      colseFormVisible(e) {
        // console.log(e)
        // 清除表单
        this.$nextTick(() => {
          this.$refs[e].resetFields()
        })
        if (e == 'addFormVisibleData') {
          this.addFormVisible = false
        } else if (e == 'editFormVisibleData') {
          this.editFormVisible = false
        } else {
          this.editPwdVisible = false
        }
      },
      // 当某一行被点击时触发
      clickRow(row, column, event) {
        this.clickRowData = row
        // console.log(row);
      },
      // 添加确认
      addConfirm() {
        this.$refs['addFormVisibleData'].validate((valid) => {
          if (valid) {
            adminAdd({
              data: this.addFormVisibleData
            }).then((res) => {
              if (res.code == 1) {
                this.addFormVisible = false
                // 清除表单
                this.$nextTick(() => {
                  this.$refs['addFormVisibleData'].resetFields()
                })
                this.$message.success('添加成功')
                // 刷新当前页
                location.reload()
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            this.$alert('请确保必填项不为空', '表单不完整', {
              confirmButtonText: '我知道了'
            })
          }
        })
      },

      // 编辑管理用户
      handleEdit(index, row) {
        var id = row.id
        passIdGet({
          id: id
        }).then(res => {
          this.editFormVisible = true
          this.editFormVisibleData = res.data
        })
        // console.log(id);
      },
      // 编辑确认
      editConfirm(e) {
        this.$refs['editFormVisibleData'].validate((valid) => {
          if (valid) {
            adminEdit({
              data: this.editFormVisibleData
            }).then(res => {
              if (res.code == 1) {
                this.editFormVisible = false
                // 清除表单
                this.$nextTick(() => {
                  this.$refs['editFormVisibleData'].resetFields()
                })
                this.$message.success('编辑成功')
                // 刷新当前页
                location.reload()
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            this.$alert('请确保必填项不为空', '表单不完整', {
              confirmButtonText: '我知道了'
            })
          }
        })
      },
      // 删除管理用户
      handleDelete(row) {
        var user_id = row.id
        this.$confirm('此操作将删除管理员, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          adminDel({
            id: user_id
          }).then((res) => {
            if (res.code == 1) {
              this.$message({
                type: 'success',
                message: '删除成功'
              })

              // 刷新当前页
              location.reload()
            } else {
              this.$message({
                type: 'info',
                message: res.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },

      // 修改密码确认
      ediePwdConfirm() {
        this.$refs['pwdFrom'].validate((valid) => {
          if (valid) {
            if (this.pwdFrom.confirm_pwd != this.pwdFrom.new_pwd) {
              this.$alert('两次输入密码不一致', '验证错误', {
                confirmButtonText: '我知道了'
              })
            } else {
              adminEditPwd({
                id: this.clickRowData.id,
                pwd: this.pwdFrom.confirm_pwd
              }).then((res) => {
                if (res.code == 1) {
                  this.editPwdVisible = false
                  // 清除表单
                  this.$nextTick(() => {
                    this.$refs['pwdFrom'].resetFields()
                  })
                  this.$message.success('修改成功')
                } else {
                  this.$message.error(res.message)
                }
              })
            }
          } else {
            this.$alert('请确保必填项不为空', '表单不完整', {
              confirmButtonText: '我知道了'
            })
          }
        })
      },

      // 标签筛选
      filterTag(value, row) {
        // console.log(row.is_super)
        return row.is_super === value
      },

      // 账号状态开关
      switchChange(e) {
        adminStatusSwitch({
          switch: e[0],
          id: e[1]
        }).then((res) => {
          if (res.code == 1) {
            if (e[0] == 2) {
              var msg = '停用成功'
            } else {
              var msg = '放行成功'
            }
            this.$message.success(msg)
          } else {
            this.$message.error(res.msg)
          }
        })
      },

      // 搜索
      searchSubmit() {
        this.loading = false
        adminList({
          page: this.currPage,
          size: this.pageSize,
          mobile: this.inputmobile,
          name: this.inputName
        }).then(res => {
          this.loading = false
          this.tableData = res.data.list
          this.total = res.data.total_num
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .box {
    margin: 20px 50px;
  }

  .button,
  .el-input {
    // margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .search-box {
    display: flex;
    justify-content: flex-end;
  }

  .search-but {
    height: 38px;
  }

  .el-input {
    width: 200px;
    height: 50px;
    margin-right: 10px;
  }
</style>